package com.zyf.spit.dao;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zyf.spit.pojo.Spit;
import com.zyf.spit.utils.Mongodb;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SpitDao {
    @Autowired
    Mongodb mongodb;
    @Autowired
    MongoTemplate mongoTemplate;

    public List<Spit> findById(String id) {
        return (List<Spit>) mongodb.select("_id", id);
    }

    public PageInfo<String> selectContentListByUserId(String userid, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Spit> spits = (List<Spit>) mongodb.select("userid", userid);
        List list = new ArrayList();
        for (Spit spit : spits) {
            list.add(spit.getContent());
        }
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    public void addThumbupById(String id) {
        Query query = new Query(Criteria.where("_id").is(id));
//        List<Spit> byId = findById(id);
//        Update update = new Update().set("thumbup", byId.get(0).getThumbup() + 1);
        Update update=new Update();
        update.inc("thumbup",1);
        mongoTemplate.updateFirst(query, update, Spit.class);
    }

    public void add(Spit spit) {
        mongodb.insert(spit);
    }

    public void addVisitsAndShare(String id, Integer visits, Integer share) {
        Query query = new Query(Criteria.where("_id").is(id));
        List<Spit> byId = findById(id);
        Update update = new Update().set("visits", byId.get(0).getVisits() + visits).set("share", byId.get(0).getShare() + share);
        mongoTemplate.updateFirst(query, update, Spit.class);
    }

    public void deleteHumbupById(String id) {
        Query query = new Query(Criteria.where("_id").is(id));
        List<Spit> byId = findById(id);
        Update update = new Update().set("thumbup", byId.get(0).getThumbup() - 1);
        mongoTemplate.updateFirst(query, update, Spit.class);
    }
}
